package com.example.apple.paopo.activity;

import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.renderscript.RenderScript;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.baoyz.actionsheet.ActionSheet;
import com.example.apple.paopo.R;
import com.example.apple.paopo.base.BaseActivity;
import com.example.apple.paopo.dialog.PaoPoDialog;
import com.example.apple.paopo.parameterCollection.PAOPOEventBusParameter;
import com.orhanobut.logger.Logger;
import com.vondear.rxtools.RxImageTool;
import com.vondear.rxtools.RxNetTool;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxPictureTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.RxToast;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.vondear.rxtools.view.dialog.RxDialogEditSureCancel;
import com.zyao89.view.zloading.ZLoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.select.Evaluator;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.b.V;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UploadBatchListener;
import jp.wasabeef.richeditor.RichEditor;

import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

/**
 * Created by apple on 17/12/18.
 */
@ContentView(R.layout.activity_messageeditor)
public class MessageEditorActivity extends BaseActivity {
    @ViewInject(R.id.messageeditor_title)
    EditText mtitle;
    @ViewInject(R.id.editor)
    RichEditor mEditor;
    String mEditorText;
    @ViewInject(R.id.tool_title)
    TextView toolText;
    @ViewInject(R.id.tool_more)
    ImageView toolMore;

    ZLoadingDialog dialog;

    SharedPreferences sharedPreferences;
    RxDialogChooseImage dialogChooseImage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        toolMore.setImageResource(R.drawable.fabu);
        toolText.setText("发布界面");
        sharedPreferences =getSharedPreferences("PAOPO",MODE_APPEND);


        mEditor = (RichEditor) findViewById(R.id.editor);
        mEditor.setEditorHeight(200);
        mEditor.setEditorFontSize(19);
        mEditor.setEditorFontColor(Color.BLACK);
        mEditor.loadCSS("style.css");
        //mEditor.setEditorBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundColor(Color.BLUE);
        //mEditor.setBackgroundResource(R.drawable.bg);
        mEditor.setPadding(10, 10, 10, 10);
        //mEditor.setBackground("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg");
        mEditor.setPlaceholder("输入内容");
        //mEditor.setInputEnabled(false);
        mEditor. setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
            @Override
            public void onTextChange(String text) {
                mEditorText=text;
                // Do Something
                Logger.d("RichEditor", "Preview " + text);
            }
        });

    }
    //查入图片
    @Event(R.id.messageeditor_tupian)
    private void setUpPicture(View view){
//        ActionSheet.createBuilder(this,getSupportFragmentManager())
//                .setCancelButtonTitle("取消")
//                .setOtherButtonTitles("短","邮箱找回")
//                .setCancelableOnTouchOutside(true)
//                .setListener(new ActionSheet.ActionSheetListener() {
//                    @Override
//                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
//
//                    }
//
//                    @Override
//                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
//                        switch (index){
//                            case 0:
//                                Intent intentphone  = new Intent(LoginActivity.this,ForgetPasswordPhoneActivity.class);
//                                startActivity(intentphone);
//                                actionSheet.dismiss();
//                                break;
//                            case 1:
//                                Intent intentemail  = new Intent(LoginActivity.this,ForgetPasswordEmailActivity.class);
//                                startActivity(intentemail);
//                                actionSheet.dismiss();
//                                break;
//                        }
//                    }
//                }).show();
         dialogChooseImage = new RxDialogChooseImage((Activity) getApplicationContext(), TITLE);
        dialogChooseImage.show();
    }


    @Event(R.id.messageeditor_lianjie)
    private void setUpLink(View view){
        final RxDialogEditSureCancel rxDialogEditSureCancel = new RxDialogEditSureCancel(mContext);//提示弹窗
        rxDialogEditSureCancel.getTitleView().setBackgroundResource(R.drawable.charulianjie);
        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               String link= rxDialogEditSureCancel.getEditText().getText().toString();
                mEditor.insertLink(link, link);
                mEditor.setAlignCenter();
//                rxDialogEditSureCancel.cancel();
//                rxDialogEditSureCancel.dismiss();
            }
        });
        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                rxDialogEditSureCancel.cancel();
//                rxDialogEditSureCancel.dismiss();
            }
        });
        rxDialogEditSureCancel.show();
    }

    @Event(R.id.messageeditor_juzuo)
    private void setAlignLeft(View view){
        mEditor.setAlignLeft();
    }

    @Event(R.id.messageeditor_juzhong)
    private void setAlignCenter(View view){
        mEditor.setAlignCenter();

    }
    @Event(R.id.messageeditor_juyou)
    private void setAlignRight(View view){
        mEditor.setAlignRight();

    }

    @Event(R.id.tool_break)
    private void breakAction(View view){
        finish();
    }

    @Event(R.id.tool_more)
    private void sendAction(View view){
       ArrayList arrayList= handlingSendText(mEditorText);
        if(!RxNetTool.isNetworkAvailable(this)){
            RxToast.error(this,"发布失败，请检查网络是否可用-0").show();
        }else {
            dialog = PaoPoDialog.getPaoPoDialog(mContext,"正在发布中,请稍后...");
            if (arrayList.size()==0){
                sendEndData(new ArrayList<String>());
            }else {
            sendImageToFromServer(arrayList);
            }
        }

    }

    //上传完图片的回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendImageToFromServerCallback(PAOPOEventBusParameter.SendImageToServer sendImageToServer) {
        if (sendImageToServer.aBoolean){
            //上传成功
            if(!RxNetTool.isNetworkAvailable(this)){
                dialog.cancel();
                dialog.dismiss();
                RxToast.error(this,"发布失败，请检查网络是否可用-1").show();
            }else {
                replaceText(sendImageToServer.list1);
                sendEndData(sendImageToServer.list1);
            }
            sendImageToServer=null;

        }else {
            //上传失败
           // dialog.cancel();
            RxToast.error(this,"发布失败，请检查网络是否可用-2").show();

        }
    }

    //准备工作全部做完后发送消息
    private void sendEndData(List<String> list1) {
        RequestParams params = new RequestParams("http://cloud.bmob.cn/91c9d2dffacfcd37/worldMessageSentAction");
        params.addQueryStringParameter("timeDestruction", String.valueOf(0));
        params.addQueryStringParameter("contentText",mEditorText);
        params.addQueryStringParameter("title",mtitle.getText().toString());
        params.addQueryStringParameter("contentImage1", list1.size()>=1?list1.get(0):"");
        params.addQueryStringParameter("contentImage2", list1.size()>=2?list1.get(1):"");
        params.addQueryStringParameter("contentImage3", list1.size()>=3?list1.get(2):"");
        params.addQueryStringParameter("token",sharedPreferences.getString("token",""));
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    if (jsonObject.getString("state").equals("YES")){
                          RxToast.success("发布成功");
                         // dialog.cancel();
                          //dialog.dismiss();
                        //  PaoPoDialog.releasePaoPoDialog();
                          finish();

                    }else {
                        RxToast.error("发布失败");
                        Logger.d("数据返回失败");
                     //   dialog.cancel();
                    }
                } catch (JSONException e) {
                    RxToast.error("发布失败");
                    Logger.d("解析失败");
                    e.printStackTrace();
                 //   dialog.cancel();
                }
                dialog.cancel();
                dialog.dismiss();
               // dialog.cancel();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                RxToast.error("发布失败");
                Logger.d("网络报错失败"+ex);
                dialog.cancel();
                dialog.dismiss();
               // dialog.cancel();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
//                RxToast.error("发布失败");
//                Logger.d("取消失败");
//                dialog.cancel();
            }
        });

    }

    //替换图片链接
    private void replaceText(List<String> list1) {
        ArrayList <String>arrayList= handlingSendText(mEditorText);
            String medi =null;
        for (int i=0;i<list1.size();i++){

            medi =mEditorText.replaceAll(arrayList.get(i),list1.get(i));
        }
        mEditorText =medi;
        Logger.d(mEditorText);
    }

    //上传图片
    private void sendImageToFromServer(ArrayList arrayList) {
        //array转string[]
        String[] strings =(String[])arrayList.toArray(new String[arrayList.size()]);
        //上传图片文件
        Bmob.uploadBatch(strings, new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> list, List<String> list1) {
                PAOPOEventBusParameter.SendImageToServer sendImageToServer =new PAOPOEventBusParameter.SendImageToServer();
                sendImageToServer.list =list;
                sendImageToServer.list1 =list1;
                sendImageToServer.aBoolean =true;
                EventBus.getDefault().post(sendImageToServer);
                //1、list-上传完成后的BmobFile集合，
                // 是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
                //2、ist1-上传文件的服务器地址
            }

            @Override
            public void onProgress(int i, int i1, int i2, int i3) {
                //1、i--表示当前第几个文件正在上传
                //2、i1--表示当前上传文件的进度值（百分比）
                //3、i2--表示总的上传文件数
                //4、i3--表示总的上传进度（百分比）

            }

            @Override
            public void onError(int i, String s) {
                PAOPOEventBusParameter.SendImageToServer sendImageToServer =new PAOPOEventBusParameter.SendImageToServer();
                sendImageToServer.aBoolean =false;
                sendImageToServer.errormsg="错误码"+i+",错误描述："+s;
                EventBus.getDefault().post(sendImageToServer);
                Logger.d("错误码"+i+",错误描述："+s);
                dialog.cancel();
                dialog.dismiss();
            }
        });
    }

    //处理文本获取到图片路径
    private ArrayList<String> handlingSendText(String mEditorText) {
        ArrayList<String> arrayList =new ArrayList<>();
        Document doc = Jsoup.parse(mEditorText);
        Elements elements =doc.select("div").select("img");
        for (int i=0;i<elements.size();i++){
            Element element = elements.get(i);
          arrayList.add(element.attr("src"));
          Logger.d(String.valueOf(arrayList));
        }
        return arrayList;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        dialogChooseImage.dismiss();
//        dialogChooseImage =null;
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    String path =RxPhotoTool.getRealFilePath(mContext,data.getData());
                    mEditor.insertImage(path, "image");
                    mEditor.setAlignCenter();
                    }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    //保存图片
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intent.setData(RxPhotoTool.imageUriFromCamera);
                    MessageEditorActivity.this.sendBroadcast(intent);
                    //this.sendBroadccast(intent);

                    String path = RxPhotoTool.getRealFilePath(mContext, RxPhotoTool.imageUriFromCamera);
                    Logger.d("图片路径："+path+","+RxPhotoTool.imageUriFromCamera.toString());
                    mEditor.insertImage(path, "image");
                    mEditor.setAlignCenter();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (mEditor != null) {
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = mEditor.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mEditor );
            }

            mEditor .stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mEditor .getSettings().setJavaScriptEnabled(false);
            mEditor .clearHistory();
            mEditor .clearView();
            mEditor .removeAllViews();

            try {
                mEditor .destroy();
            } catch (Throwable ex) {

            }
        }
        super.onDestroy();
        //   if( dialogChooseImage != null) {
        //    }
    }
    //
//    public File getFileByUri(Uri uri) {
//        String path = null;
//        if ("file".equals(uri.getScheme())) {
//            path = uri.getEncodedPath();
//            if (path != null) {
//                path = Uri.decode(path);
//                ContentResolver cr = mContext.getContentResolver();
//                StringBuffer buff = new StringBuffer();
//                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");
//                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }, buff.toString(), null, null);
//                int index = 0;
//                int dataIdx = 0;
//                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
//                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
//                    index = cur.getInt(index);
//                    dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//                    path = cur.getString(dataIdx);
//                }
//                cur.close();
//                if (index == 0) {
//                } else {
//                    Uri u = Uri.parse("content://media/external/images/media/" + index);
//                    System.out.println("temp uri is :" + u);
//                }
//            }
//            if (path != null) {
//                return new File(path);
//            }
//        } else if ("content".equals(uri.getScheme())) {
//            // 4.2.2以后
//            String[] proj = { MediaStore.Images.Media.DATA };
//            Cursor cursor = mContext.getContentResolver().query(uri, proj, null, null, null);
//            if (cursor.moveToFirst()) {
//                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                path = cursor.getString(columnIndex);
//            }
//            cursor.close();
//
//            return new File(path);
//        } else {
//            Logger.i( "Uri Scheme:" + uri.getScheme());
//        }
//        return null;
//    }

//    private String obtainImagePath(Uri uri) {
//        String path = "";
//        Cursor cursor = getContentResolver().query(uri, null, null, null,null);
//        if (cursor != null && cursor.moveToFirst()) {
//          path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
//        }
//
//        return path;
//    }
}
